<template>
  <div class="exam-room">
    <!-- 考试头部信息 -->
    <div class="exam-header">
      <div class="exam-info">
        <h2>{{ examInfo.name }}</h2>
        <p>{{ examInfo.description }}</p>
      </div>
      <div class="exam-timer">
        <div class="timer-display">
          <el-icon><Clock /></el-icon>
          <span class="time-left">{{ formatTime(timeLeft) }}</span>
        </div>
        <div class="progress-info">
          <span>{{ currentQuestionIndex + 1 }} / {{ questions.length }}</span>
        </div>
      </div>
    </div>

    <!-- 考试内容区域 -->
    <div class="exam-content">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-loading />
        <p>正在加载试题，请稍候...</p>
      </div>
      
      <!-- 考试题目内容 -->
      <div v-else-if="questions.length > 0" class="question-container">
        <!-- 题目内容 -->
        <div class="question-content">
          <div class="question-header">
            <span class="question-number">第 {{ currentQuestionIndex + 1 }} 题</span>
            <span class="question-type">{{ getQuestionTypeText(currentQuestion.type) }}</span>
            <span class="question-score">{{ currentQuestion.score }}分</span>
          </div>
          
          <div class="question-body">
            <p>{{ currentQuestion.content }}</p>
          </div>

          <!-- 选择题选项 -->
          <div v-if="currentQuestion.type === 'singleChoice'" class="question-options">
            <el-radio-group v-model="currentAnswer" @change="saveAnswer">
              <div 
                v-for="(option, index) in currentQuestion.options" 
                :key="index"
                class="option-item"
              >
                <el-radio :label="String.fromCharCode(65 + index)">
                  <span class="option-label">{{ String.fromCharCode(65 + index) }}.</span>
                  <span class="option-text">{{ option }}</span>
                </el-radio>
              </div>
            </el-radio-group>
          </div>

          <!-- 多选题选项 -->
          <div v-if="currentQuestion.type === 'multipleChoice'" class="question-options">
            <el-checkbox-group v-model="currentAnswer" @change="saveAnswer">
              <div 
                v-for="(option, index) in currentQuestion.options" 
                :key="index"
                class="option-item"
              >
                <el-checkbox :label="String.fromCharCode(65 + index)">
                  <span class="option-label">{{ String.fromCharCode(65 + index) }}.</span>
                  <span class="option-text">{{ option }}</span>
                </el-checkbox>
              </div>
            </el-checkbox-group>
          </div>

          <!-- 判断题选项 -->
          <div v-if="currentQuestion.type === 'trueFalse'" class="question-options">
            <el-radio-group v-model="currentAnswer" @change="saveAnswer">
              <div class="option-item">
                <el-radio label="true">
                  <span class="option-label">正确</span>
                </el-radio>
              </div>
              <div class="option-item">
                <el-radio label="false">
                  <span class="option-label">错误</span>
                </el-radio>
              </div>
            </el-radio-group>
          </div>

          <!-- 填空题输入 -->
          <div v-if="currentQuestion.type === 'fillBlank'" class="question-input">
            <el-input
              v-model="currentAnswer"
              type="text"
              placeholder="请输入答案"
              @input="saveAnswer"
              clearable
            />
          </div>
        </div>

        <!-- 题目导航 -->
        <div class="question-navigation">
          <div class="nav-buttons">
            <el-button 
              :disabled="currentQuestionIndex === 0"
              @click="previousQuestion"
            >
              上一题
            </el-button>
            <el-button 
              :disabled="currentQuestionIndex === questions.length - 1"
              @click="nextQuestion"
            >
              下一题
            </el-button>
          </div>
          
          <div class="question-grid">
            <div 
              v-for="(question, index) in questions" 
              :key="index"
              class="question-item"
              :class="{
                'current': index === currentQuestionIndex,
                'answered': answers[index] !== undefined && answers[index] !== '',
                'unanswered': answers[index] === undefined || answers[index] === ''
              }"
              @click="goToQuestion(index)"
            >
              {{ index + 1 }}
            </div>
          </div>
        </div>
      </div>
      
      <!-- 无试题状态 -->
      <div v-else class="no-questions">
        <el-empty description="暂无试题" />
      </div>
    </div>

    <!-- 考试底部操作 -->
    <div class="exam-footer">
      <div class="exam-actions">
        <el-button type="warning" @click="showSubmitConfirm">
          提交试卷
        </el-button>
        <el-button @click="saveProgress">
          保存进度
        </el-button>
      </div>
    </div>

    <!-- 提交确认对话框 -->
    <el-dialog
      v-model="submitDialogVisible"
      title="提交确认"
      width="400px"
      :close-on-click-modal="false"
    >
      <div class="submit-confirm">
        <p>确定要提交试卷吗？</p>
        <div class="submit-stats">
          <div class="stat-item">
            <span class="label">已答题数：</span>
            <span class="value">{{ answeredCount }}</span>
          </div>
          <div class="stat-item">
            <span class="label">未答题数：</span>
            <span class="value">{{ unansweredCount }}</span>
          </div>
          <div class="stat-item">
            <span class="label">剩余时间：</span>
            <span class="value">{{ formatTime(timeLeft) }}</span>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="submitDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitExamBtn" :loading="submitting">
            确认提交
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 离开确认 -->
    <el-dialog
      v-model="leaveDialogVisible"
      title="离开确认"
      width="400px"
      :close-on-click-modal="false"
    >
      <div class="leave-confirm">
        <p>确定要离开考试页面吗？</p>
        <p class="warning">离开后考试进度将自动保存，您可以稍后继续。</p>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="leaveDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmLeave">确认离开</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Clock } from '@element-plus/icons-vue'
import { submitExam, saveExamProgress,startExam, getExamResult, questionList, getExamDetail } from '@/api/system'

const router = useRouter()
const route = useRoute()

// 考试信息
const examInfo = ref({
  name: '',
  description: '',
  duration: 0,
  totalQuestions: 0
})

// 考试题目
const questions = ref([])
const currentQuestionIndex = ref(0)
const answers = ref({})
const currentAnswer = ref('')
const msgId = ref('')

// 考试状态
const timeLeft = ref(0)
const timer = ref(null)
const submitting = ref(false)
const submitDialogVisible = ref(false)
const leaveDialogVisible = ref(false)
const loading = ref(true) // 新增加载状态

// 计算属性
const currentQuestion = computed(() => questions.value[currentQuestionIndex.value] || {})

const answeredCount = computed(() => {
  return Object.keys(answers.value).filter(key => 
    answers.value[key] !== undefined && answers.value[key] !== ''
  ).length
})

const unansweredCount = computed(() => {
  return questions.value.length - answeredCount.value
})

// 获取题目类型文本
const getQuestionTypeText = (type) => {
  const typeMap = {
    'singleChoice': '单选题',
    'multipleChoice': '多选题',
    'trueFalse': '判断题',
    'fillBlank': '填空题'
  }
  return typeMap[type] || '未知类型'
}

// 格式化时间
const formatTime = (seconds) => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60
  
  if (hours > 0) {
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }
  return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 保存答案
const saveAnswer = () => {
  answers.value[currentQuestionIndex.value] = currentAnswer.value
  // 实时保存到服务器
//  saveProgress()
}

// 保存进度
const saveProgress = async () => {
  try {
//    const examId = route.query.examId
    if (!msgId.value) {
      console.warn('缺少考试ID，无法保存进度')
      return
    }

    // 调用真实的保存进度接口
    await saveExamProgress({
      examId: msgId.value,
      sessionId: route.query.sessionId || `session_${Date.now()}`,
      questionIndex: currentQuestionIndex.value,
      answer: currentAnswer.value,
      timestamp: new Date().toISOString(),
      answers: answers.value,
      timeLeft: timeLeft.value
    })
    
    console.log('进度保存成功')
  } catch (error) {
    console.error('保存进度失败:', error)
    // 不显示错误消息，避免影响用户体验
  }
}

// 上一题
const previousQuestion = () => {
  if (currentQuestionIndex.value > 0) {
    currentQuestionIndex.value--
    currentAnswer.value = answers.value[currentQuestionIndex.value] || ''
  }
}

// 下一题
const nextQuestion = () => {
  if (currentQuestionIndex.value < questions.value.length - 1) {
    currentQuestionIndex.value++
    currentAnswer.value = answers.value[currentQuestionIndex.value] || ''
  }
}

// 跳转到指定题目
const goToQuestion = (index) => {
  currentQuestionIndex.value = index
  currentAnswer.value = answers.value[index] || ''
}

// 显示提交确认
const showSubmitConfirm = () => {
  submitDialogVisible.value = true
}

// 提交考试
const submitExamBtn = async () => {
  try {
    submitting.value = true
    
//    const examId = route.query.examId
    if (!msgId.value) {
      ElMessage.error('缺少考试ID参数')
      return
    }

//    answers.value[currentQuestionIndex.value] = currentAnswer.value
    const recordDetailReqVOS =  questions.value.map((r,index)=>{
      return {
        recordId: msgId.value,
        questionId: r.id,
        userAnswer: answers.value[index],
      }
    })
    // 调用真实的提交考试接口
    const response = await submitExam(msgId.value, {
      recordId: msgId.value,
      recordDetailReqVOS:recordDetailReqVOS,
//      sessionId: route.query.sessionId || `session_${Date.now()}`,
//      answers: answers.value,
//      timeLeft: timeLeft.value,
//      submitTime: new Date().toISOString(),
//      totalQuestions: questions.value.length,
//      answeredCount: answeredCount.value
    })
//    console.log(111,response)
    if (response && response.data) {
      ElMessage.success('考试提交成功！')
      submitDialogVisible.value = false
      
      // 跳转到考试结果页面
      router.push({
        path: '/exam-result',
        query: { 
//          resultId: response.data.resultId || `result_${Date.now()}`,
          resultId: msgId.value,
//          score: response.data.score || calculateScore(),
//          totalQuestions: questions.value.length,
//          correctAnswers: response.data.correctAnswers || calculateCorrectAnswers()
        }
      })
    } else {
      throw new Error('提交失败，未收到有效响应')
    }
    
  } catch (error) {
    console.error('提交考试失败:', error)
    ElMessage.error('提交失败，请稍后重试')
  } finally {
    submitting.value = false
  }
}

// 计算分数
const calculateScore = () => {
  let totalScore = 0
  Object.keys(answers.value).forEach(index => {
    const question = questions.value[index]
    if (question && answers.value[index]) {
      // 简单的评分逻辑，实际应该根据正确答案判断
      totalScore += question.score
    }
  })
  return Math.min(totalScore, 100) // 最高100分
}

// 计算正确答案数量
const calculateCorrectAnswers = () => {
  // 模拟正确答案数量
  return Math.floor(Math.random() * questions.value.length * 0.8) + Math.floor(questions.value.length * 0.6)
}

// 开始倒计时
const startTimer = () => {
  timer.value = setInterval(() => {
    if (timeLeft.value > 0) {
      timeLeft.value--
    } else {
      // 时间到，自动提交
      clearInterval(timer.value)
      ElMessage.warning('考试时间已到，系统将自动提交试卷')
      submitExam()
    }
  }, 1000)
}

// 停止倒计时
const stopTimer = () => {
  if (timer.value) {
    clearInterval(timer.value)
    timer.value = null
  }
}
// 初始化考试数据
const initExam = async () => {
  try {
    // 从路由参数获取考试ID
    const examId = route.query.examId
    if (!examId) {
      ElMessage.error('缺少考试ID参数')
      router.push('/exams')
      return
    }

    const res = await startExam(examId, {
//      userId: route.query.userId || 'default_user', // 可以从用户状态获取
//      timestamp: new Date().toISOString(),
      id: examId
    })
    msgId.value = res.msg
    const resp = await getExamResult(msgId.value)
    const examObj = resp.data.examRecordsEntity
    const response = await questionList({examId: examObj.examId})
    const responseTwo = await getExamDetail(examObj.examId)

    if (response && response.rows) {
      const examData = response.rows
      // 设置考试信息
      examInfo.value = {
        name: responseTwo.data.examName || '日语考试',
        description: responseTwo.data.description || '测试日语基础知识',
        duration: responseTwo.data.durationMin* 60 || 60 * 60, // 默认60分钟
        totalQuestions: responseTwo.data.questionNum || 0
      }
      
      // 设置试题数据
      if (examData && Array.isArray(examData)) {
        questions.value = examData.map((q, index) => ({
          id: q.id || `q${index + 1}`,
          type: q.type || 'singleChoice',
          content: q.content || q.question || '',
          options: [q.option_a,q.option_b,q.option_c,q.option_d] || [],
          score: q.score || 2,
//          correctAnswer: q.correctAnswer || '',
//          explanation: q.explanation || ''
        }))
      } else {
        // 如果没有试题数据，使用默认数据
        questions.value = [
          {
            id: 'q1',
            type: 'singleChoice',
            content: '正在加载试题...',
            options: ['加载中...'],
            score: 2
          }
        ]
      }
      
      // 设置考试时间
      timeLeft.value = examInfo.value.duration
      
      // 开始倒计时
      startTimer()
      
      ElMessage.success('考试开始！')
    } else {
      throw new Error('接口返回数据格式错误')
    }
    
  } catch (error) {
    console.error('获取考试数据失败:', error)
    ElMessage.error('获取考试数据失败，请稍后重试')
    
    // 使用默认数据作为备用
    examInfo.value = {
      name: '日语N5基础语法考试',
      description: '测试日语N5级别的基础语法知识，包括助词、动词变化等',
      duration: 60 * 60, // 60分钟
      totalQuestions: 10
    }
    
    questions.value = [
      {
        id: 'q1',
        type: 'singleChoice',
        content: '「は」和「が」的区别是什么？',
        options: ['A. 「は」表示主题，「が」表示主语', 'B. 「は」表示主语，「が」表示主题', 'C. 两者没有区别', 'D. 根据语境决定'],
        score: 2
      },
      {
        id: 'q2',
        type: 'singleChoice',
        content: '在商务场合，如何礼貌地拒绝邀请？',
        options: ['A. 「参加しません」', 'B. 「申し訳ございませんが、今回は参加できません」', 'C. 「いやです」', 'D. 「だめです」'],
        score: 2
      }
    ]
    
    timeLeft.value = examInfo.value.duration
    startTimer()
  } finally {
    loading.value = false // 结束加载
  }
}

// 页面离开确认
const handleBeforeUnload = (e) => {
  e.preventDefault()
  e.returnValue = '确定要离开考试页面吗？'
}

// 确认离开
const confirmLeave = () => {
  leaveDialogVisible.value = false
  router.push('/exams')
}

// 生命周期
onMounted(async () => {
  await initExam()
  window.addEventListener('beforeunload', handleBeforeUnload)
})

onBeforeUnmount(() => {
  stopTimer()
})

onUnmounted(() => {
  window.removeEventListener('beforeunload', handleBeforeUnload)
})
</script>

<style scoped>
.exam-room {
  min-height: 60vh;
  background: #f5f7fa;
  display: flex;
  flex-direction: column;
}

.exam-header {
  background: white;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.exam-info h2 {
  margin: 0 0 5px 0;
  color: #2c3e50;
  font-size: 1.5rem;
}

.exam-info p {
  margin: 0;
  color: #666;
  font-size: 0.9rem;
}

.exam-timer {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.timer-display {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 1.2rem;
  font-weight: bold;
  color: #f56c6c;
}

.progress-info {
  font-size: 0.9rem;
  color: #666;
}

.exam-content {
  flex: 1;
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
}

/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 300px; /* 确保有足够的空间显示加载状态 */
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 30px;
}

.loading-container .el-loading-component {
  margin-bottom: 20px;
}

.loading-container p {
  color: #666;
  font-size: 1rem;
}

/* 无试题状态 */
.no-questions {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px; /* 确保有足够的空间显示无试题状态 */
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 30px;
}

.no-questions .el-empty__description {
  color: #909399;
}

.question-container {
  display: grid;
  grid-template-columns: 1fr 300px;
  gap: 30px;
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.question-content {
  flex: 1;
}

.question-header {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.question-number {
  font-size: 1.1rem;
  font-weight: bold;
  color: #409eff;
}

.question-type {
  background: #f0f9ff;
  color: #409eff;
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 0.8rem;
}

.question-score {
  background: #f0f9ff;
  color: #67c23a;
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 0.8rem;
  font-weight: bold;
}

.question-body {
  margin-bottom: 30px;
}

.question-body p {
  font-size: 1.1rem;
  line-height: 1.6;
  color: #2c3e50;
  margin: 0;
}

.question-options {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.option-item {
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.option-item:hover {
  border-color: #409eff;
  background: #f0f9ff;
}

.option-label {
  font-weight: bold;
  color: #409eff;
  margin-right: 10px;
}

.option-text {
  color: #2c3e50;
}

.question-input {
  margin-top: 20px;
}

.question-navigation {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.nav-buttons {
  display: flex;
  gap: 10px;
}

.question-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 8px;
}

.question-item {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  cursor: pointer;
  font-size: 0.9rem;
  font-weight: 500;
  transition: all 0.3s;
}

.question-item:hover {
  border-color: #409eff;
  color: #409eff;
}

.question-item.current {
  background: #409eff;
  color: white;
  border-color: #409eff;
}

.question-item.answered {
  background: #67c23a;
  color: white;
  border-color: #67c23a;
}

.question-item.unanswered {
  background: #f5f7fa;
  color: #909399;
}

.exam-footer {
  background: white;
  padding: 20px;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.exam-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
}

.submit-confirm {
  text-align: center;
}

.submit-confirm p {
  margin: 0 0 20px 0;
  font-size: 1.1rem;
  color: #2c3e50;
}

.submit-stats {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #eee;
}

.stat-item .label {
  color: #666;
}

.stat-item .value {
  font-weight: bold;
  color: #2c3e50;
}

.leave-confirm {
  text-align: center;
}

.leave-confirm p {
  margin: 0 0 10px 0;
  color: #2c3e50;
}

.leave-confirm .warning {
  color: #f56c6c;
  font-size: 0.9rem;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .question-container {
    grid-template-columns: 1fr;
    gap: 20px;
  }
  
  .exam-header {
    flex-direction: column;
    gap: 20px;
    text-align: center;
  }
  
  .question-grid {
    grid-template-columns: repeat(4, 1fr);
  }
  
  .exam-actions {
    flex-direction: column;
    gap: 10px;
  }
}
</style>
